const { server } = require('../config')

const Koa = require('koa2')
const parse = require('koa-bodyparser')
const cors = require('@koa/cors')
const app = new Koa();
const catchError = require('../middleware/exception')
const Router = require('koa-router')
const requireDIrectory = require('require-directory')
const koaStatic = require('koa-static')
const path = require('path')

class Server{
  constructor(){
    this.config = server;
  }

  loadRouters(){
    const apiDirectory = global.ROOTPATH + '/routers' + (server.api || '/');
    console.log('加载路由版本: ' + server.api);
    requireDIrectory(module, apiDirectory, {
      visit: whenLoadModule
    })

    function whenLoadModule(obj){
      if(obj instanceof Router){
        app.use(obj.routes())
      }
    }
  }

  run(){
    app
      .use(cors())
      .use(catchError)
      .use(koaStatic(path.join(__dirname, '../static')))
      .use(parse())

    this.loadRouters()

    app.listen(this.config.port, () => {
      console.log(`Blog-api服务启动成功, ::${this.config.port}`);
    })
  }
}

module.exports = Server;